/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.inv.input.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.erp.inv.input.dao.model.*;
import com.erp.inv.output.dao.model.InvOutputHead;
import com.erp.inv.output.dao.model.InvOutputLine;
import com.erp.inv.output.service.InvOutputHeadService;
import com.erp.inv.output.service.InvOutputLineService;
import com.erp.inv.stock.dao.model.InvStock;
import com.erp.inv.stock.service.InvStockService;
import com.erp.masterdata.common.utils.StringUtil;
import com.erp.order.dn.dao.model.DeliveryNoteHead;
import com.erp.order.dn.service.DeliveryNoteHeadService;
import com.erp.order.supply.model.SupplyMaterialBeanVo;
import com.erp.order.supply.model.SupplyMaterialDetailVO;
import com.erp.order.supply.model.SupplyMaterialVO;
import com.erp.order.supply.service.SupplyMaterialService;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.common.ap.invoice.service.ApInvoiceHeadService;
import com.erp.common.voucher.service.FinVoucherBillRService;
import com.erp.common.voucher.service.FinVoucherHeadService;
import com.erp.common.voucher.service.FinVoucherModelHeadService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.inv.input.dao.data.DataBox;
import com.erp.inv.input.service.InvInputHeadService;
import com.erp.inv.input.service.InvInputLineService;
import com.erp.inv.inputeco.service.InputEcoService;
import com.erp.inv.inputeco.service.InvInputHeadMService;
import com.erp.inv.warehouse.dao.model.InvWarehouse;
import com.erp.inv.warehouse.service.InvWarehouseService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.vendor.dao.model.MdVendor;
import com.erp.masterdata.vendor.dao.model.MdVendorContact;
import com.erp.order.po.dao.model.PoHead;
import com.erp.order.po.dao.model.PoHeadCO;
import com.erp.order.po.dao.model.PoLine;
import com.erp.order.po.service.PoHeadService;
import com.erp.order.po.service.PoLineService;

@Controller
@RequestMapping("/web/invInputHead")
public class InvInputHeadWebController extends CuxControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(InvInputHeadWebController.class);
    
    //服务层注入
    @Autowired
    private InvInputHeadService invInputHeadService;
    @Autowired
    private InvInputLineService invInputLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private PoHeadService poHeadService;
    @Autowired
    private PoLineService poLineService;
    @Autowired
    private InvWarehouseService invWarehouseService;
    @Autowired
    @Qualifier("finVoucherModelHeadServiceCommon")
    private FinVoucherModelHeadService finVoucherModelHeadService;
    @Autowired
    @Qualifier("finVoucherHeadServiceCommon")
    private FinVoucherHeadService finVoucherHeadService;
    @Autowired
    @Qualifier("finVoucherBillRServiceCommon")
    private FinVoucherBillRService finVoucherBillRService;
    @Autowired
    @Qualifier("apInvoiceHeadServiceCommon")
    private ApInvoiceHeadService apInvoiceHeadService;
    @Autowired
    private InputEcoService inputEcoService;
    @Autowired
    private InvInputHeadMService invInputHeadMService;
    @Autowired
    private DeliveryNoteHeadService deliveryNoteHeadService;

    @Autowired
    private SupplyMaterialService supplyMaterialService;
    @Autowired
    private InvStockService invStockService;
    @Autowired
    private InvOutputHeadService invOutputHeadService;
    @Autowired
    private InvOutputLineService invOutputLineService;
    
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getInvInputHeadList");
    }


    @RequestMapping("changeInput")
    public String changeInput(){

        return "invInput/invInputLineEdit";
    }

    
    /**
     * 
     * @description 入库查询数据列表
     * @date 2020-08-20 17:21:04
     * @author 
     * @param pages
     * @param invInputHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHeadList")
    public String getInvInputHeadList(Pages pages, InvInputHeadCO invInputHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        invInputHeadCO.setInputType("IN");
        //分页查询数据
        List<InvInputHead> invInputHeadList = this.invInputHeadService.getDataObjectsForDataAuth("", pages, invInputHeadCO);
        
        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        Map inputTypeMap = DataBox.getInputTypeMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }
        
        //循环设置职员和组织信息
        for(InvInputHead invInputHead: invInputHeadList) {
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            if(StringUtils.isNotEmpty(invInputHead.getDepartmentCode())){
                invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            }
        }

        //页面属性设置
        model.addAttribute("invInputHeadList", invInputHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT");
        
        return "basic.jsp?content=invInput/invInputList";
    }


    /**
     *
     * @description 退货查询数据列表
     * @date 2020-08-20 17:21:04
     * @author
     * @param pages
     * @param invInputHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHeadReturnList")
    public String getInvInputHeadReturnList(Pages pages, InvInputHeadCO invInputHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }

        invInputHeadCO.setInputType("RETURN");
        //分页查询数据
        List<InvInputHead> invInputHeadList = this.invInputHeadService.getDataObjectsForDataAuth("", pages, invInputHeadCO);

        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        Map inputTypeMap = DataBox.getInputTypeMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }

        //循环设置职员和组织信息
        for(InvInputHead invInputHead: invInputHeadList) {
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            if(StringUtils.isNotEmpty(invInputHead.getDepartmentCode())){
                invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            }
        }

        //页面属性设置
        model.addAttribute("invInputHeadList", invInputHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT");

        return "basic.jsp?content=invInput/invInputReturnList";
    }


    /**
     *
     * @description 换货查询数据列表
     * @date 2020-08-20 17:21:04
     * @author
     * @param pages
     * @param invInputHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHeadSwapList")
    public String getInvInputHeadSwapList(Pages pages, InvInputHeadCO invInputHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        invInputHeadCO.setInputType("SWAP");
        //分页查询数据
        List<InvInputHead> invInputHeadList = this.invInputHeadService.getDataObjectsForDataAuth("", pages, invInputHeadCO);

        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        Map inputTypeMap = DataBox.getInputTypeMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }

        //循环设置职员和组织信息
        for(InvInputHead invInputHead: invInputHeadList) {
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            if(StringUtils.isNotEmpty(invInputHead.getDepartmentCode())){
                invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            }
        }

        //页面属性设置
        model.addAttribute("invInputHeadList", invInputHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT");

        return "basic.jsp?content=invInput/invInputSwapList";
    }



    
    /**
     * 
     * @description 入库查询单条数据
     * @date 2020-08-20 17:21:04
     * @author 
     * @param invInputHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHead")
    public String getInvInputHead(InvInputHeadBase invInputHead, Model model) {



        //处理图片逗号
        String file = invInputHead.getFile();
        if(StringUtils.isNotEmpty(file)){
            file = file + ",";
            invInputHead.setFile(file);
        }
        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        //Map inputTypeMap = DataBox.getInputTypeMap();
        Map<String, String> inputTypeMap = new LinkedHashMap<String, String>();
        inputTypeMap.put("IN","入库");
        //入库方式
        Map<String, String> inputMannerMap = new LinkedHashMap<String, String>();
        inputMannerMap.put("0","直入直出");
        inputMannerMap.put("1","其他");
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }
        
        //查询要编辑的数据
        if(invInputHead!=null&&StringUtils.isNotBlank(invInputHead.getInputHeadCode())) {
            
            //根据version请求参数，判断数据从原表获取还是变更表获取
            if(invInputHead.getVersion()!=null&&invInputHead.getVersion()>0) {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadMService.getDataObject(invInputHead.getInputHeadCode(), invInputHead.getVersion());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }else {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadService.getDataObject(invInputHead.getInputHeadCode());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }
            
            //设置显示字段
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            //仓库地址
            if(StringUtils.isNotBlank(invInputHead.getWarehouseCode())) {
                invInputHead.setWarehouseAddress(warehouseMap.get(invInputHead.getWarehouseCode()).getWarehouseAddress());
            }
            
            //获取发货单单信息
            DeliveryNoteHead noteHead = deliveryNoteHeadService.getDataObjectByCode(invInputHead.getInputSourceHeadCode());
            if(ObjectUtils.isNotEmpty(noteHead)){
                invInputHead.setInputSourceHeadName(noteHead.getDeliveryName());
                invInputHead.setVendorName(noteHead.getSupplier());
                invInputHead.setVendorContactDesc(noteHead.getContacts());
            }
        }else {
            //初始化默认字段
            invInputHead.setStatus("NEW");

            //入库单编码生成
            String inputHeadCode = invInputHead.getInputHeadCode();
            if(StringUtils.isNotEmpty(inputHeadCode)){

            }else{
                String code = "IN" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN");
                invInputHead.setInputHeadCode(code);
            }
            
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            invInputHead.setStaffCode(staffInfo.getStaffCode());
            invInputHead.setDepartmentCode(staffInfo.getDepartmentCode());
            invInputHead.setStaffName(staffInfo.getStaffName());
            invInputHead.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        
        
        //页面属性设置
        model.addAttribute("invInputHead", invInputHead);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("inputMannerMap",inputMannerMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT", invInputHead.getInputHeadCode());
        
        return "basic.jsp?content=invInput/invInputEdit";
    }


    /**
     *
     * @description 退货查询单条数据
     * @date 2020-08-20 17:21:04
     * @author
     * @param invInputHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHeadRetrun")
    public String getInvInputHeadRetrun(InvInputHeadBase invInputHead, Model model) {
        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        //Map inputTypeMap = DataBox.getInputTypeMap();
        Map<String, String> inputTypeMap = new LinkedHashMap<String, String>();
        inputTypeMap.put("RETURN","退货");
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }

        //查询要编辑的数据
        if(invInputHead!=null&&StringUtils.isNotBlank(invInputHead.getInputHeadCode())) {

            //根据version请求参数，判断数据从原表获取还是变更表获取
            if(invInputHead.getVersion()!=null&&invInputHead.getVersion()>0) {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadMService.getDataObject(invInputHead.getInputHeadCode(), invInputHead.getVersion());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }else {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadService.getDataObject(invInputHead.getInputHeadCode());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }

            //设置显示字段
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            //仓库地址
            if(StringUtils.isNotBlank(invInputHead.getWarehouseCode())) {
                invInputHead.setWarehouseAddress(warehouseMap.get(invInputHead.getWarehouseCode()).getWarehouseAddress());
            }

            //获取发货单单信息
            DeliveryNoteHead noteHead = deliveryNoteHeadService.getDataObjectByCode(invInputHead.getInputSourceHeadCode());
            if(ObjectUtils.isNotEmpty(noteHead)){
                invInputHead.setInputSourceHeadName(noteHead.getDeliveryName());
                invInputHead.setVendorName(noteHead.getSupplier());
                invInputHead.setVendorContactDesc(noteHead.getContacts());
            }
        }else {
            //初始化默认字段
            invInputHead.setStatus("NEW");

            //退货单编码生成
            String inputHeadCode = invInputHead.getInputHeadCode();
            if(StringUtils.isNotEmpty(inputHeadCode)){

            }else{
                String code = "RE" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("RETURN");
                invInputHead.setInputHeadCode(code);
            }


            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            invInputHead.setStaffCode(staffInfo.getStaffCode());
            invInputHead.setDepartmentCode(staffInfo.getDepartmentCode());
            invInputHead.setStaffName(staffInfo.getStaffName());
            invInputHead.setDepartmentName(staffInfo.getDepartmentName());
        }



        //页面属性设置
        model.addAttribute("invInputHead", invInputHead);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT", invInputHead.getInputHeadCode());

        return "basic.jsp?content=invInput/invInputReturnEdit";
    }



    /**
     *
     * @description 换货查询单条数据
     * @date 2020-08-20 17:21:04
     * @author
     * @param invInputHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputHeadSwap")
    public String getInvInputHeadSwap(InvInputHeadBase invInputHead, Model model) {
        //入库状态
        Map inputStatusMap = DataBox.getInputStatusMap();
        //来源类型
        Map deliveryMethodMap = DataBox.getDeliveryMethodMap();
        //入库类型
        //Map inputTypeMap = DataBox.getInputTypeMap();
        Map<String, String> inputTypeMap = new LinkedHashMap<String, String>();
        inputTypeMap.put("SWAP","换货");
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }

        //查询要编辑的数据
        if(invInputHead!=null&&StringUtils.isNotBlank(invInputHead.getInputHeadCode())) {

            //根据version请求参数，判断数据从原表获取还是变更表获取
            if(invInputHead.getVersion()!=null&&invInputHead.getVersion()>0) {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadMService.getDataObject(invInputHead.getInputHeadCode(), invInputHead.getVersion());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }else {
                InvInputHeadBase invInputHeadTemp = this.invInputHeadService.getDataObject(invInputHead.getInputHeadCode());
                if(invInputHeadTemp!=null) {
                    invInputHead = invInputHeadTemp;
                }
            }

            //设置显示字段
            invInputHead.setStaffName(this.hrCommonService.getHrStaff(invInputHead.getStaffCode()).getStaffName());
            invInputHead.setDepartmentName(this.hrCommonService.getHrDepartment(invInputHead.getDepartmentCode()).getDepartmentName());
            //仓库地址
            if(StringUtils.isNotBlank(invInputHead.getWarehouseCode())) {
                invInputHead.setWarehouseAddress(warehouseMap.get(invInputHead.getWarehouseCode()).getWarehouseAddress());
            }

            //获取发货单单信息
            DeliveryNoteHead noteHead = deliveryNoteHeadService.getDataObjectByCode(invInputHead.getInputSourceHeadCode());
            if(ObjectUtils.isNotEmpty(noteHead)){
                invInputHead.setInputSourceHeadName(noteHead.getDeliveryName());
                invInputHead.setVendorName(noteHead.getSupplier());
                invInputHead.setVendorContactDesc(noteHead.getContacts());
            }
        }else {
            //初始化默认字段
            invInputHead.setStatus("NEW");

            //换货单编码生成
            String inputHeadCode = invInputHead.getInputHeadCode();
            if(StringUtils.isNotEmpty(inputHeadCode)){

            }else{
                String code = "SW" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("SWAP");
                invInputHead.setInputHeadCode(code);
            }


            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            invInputHead.setStaffCode(staffInfo.getStaffCode());
            invInputHead.setDepartmentCode(staffInfo.getDepartmentCode());
            invInputHead.setStaffName(staffInfo.getStaffName());
            invInputHead.setDepartmentName(staffInfo.getDepartmentName());
        }



        //页面属性设置
        model.addAttribute("invInputHead", invInputHead);
        model.addAttribute("inputStatusMap", inputStatusMap);
        model.addAttribute("deliveryMethodMap", deliveryMethodMap);
        model.addAttribute("inputTypeMap", inputTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("warehouseMap", warehouseMap);
        //工作流属性
//        this.setWorkflowModel(model, "INPUT", invInputHead.getInputHeadCode());

        return "basic.jsp?content=invInput/invInputSwapEdit";
    }



    
    /**
     * 
     * @description 获取采购订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectPOModal")
    public String getSelectPOModal(Pages pages, PoHeadCO poHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        poHeadCO.setStatus("CONFIRM");
        poHeadCO.setApproveStatus("APPROVE");
        List<PoHead> poHeadList = this.poHeadService.getDataObjects(pages, poHeadCO);
        
        //采购订单类型
        Map poTypeMap = this.datasetCommonService.getPOType();
        //状态
        Map poStatusMap = com.erp.order.po.dao.data.DataBox.getPoStatusMap();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //获取项目
        Map projectMap = this.masterDataCommonService.getProjectMap();
        
        //循环设置职员和组织信息
        for(PoHead poHead: poHeadList) {
            poHead.setStaffName(this.hrCommonService.getHrStaff(poHead.getStaffCode()).getStaffName());
            poHead.setDepartmentName(this.hrCommonService.getHrDepartment(poHead.getDepartmentCode()).getDepartmentName());
            //获取联系人信息
            MdVendor mdVendor = this.masterDataCommonService.getMdVendorInfoCache(poHead.getVendorCode());
            if(mdVendor!=null) {
                List<MdVendorContact> mdVendorContactList = mdVendor.getMdVendorContactList();
                if(mdVendorContactList.size()>0) {
                    poHead.setVendorContactDesc(mdVendorContactList.get(0).getContactName()+"；电话"+mdVendorContactList.get(0).getContactTelephone());
                }
            }
        }
        
        //页面属性设置
        model.addAttribute("poHeadList", poHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("projectMap", projectMap);
        
        return "invInput/pop/selectPOModal";
    }
    /**
     *
     * @description 获取采购订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectDeliveryNoteModal")
    public String getSelectDeliveryNoteModal(Pages pages, SupplyMaterialBeanVo supplyMaterialBeanVo, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }

        //分页查询数据1 10 7 2
        /*deliveryNoteHeadCO.setStatus("CONFIRM");
        List<DeliveryNoteHead> deliveryNoteHeadList = this.deliveryNoteHeadService.getDataObjects(pages, deliveryNoteHeadCO);*/

        datasetCommonService.getDictByKey("");

        /**
         * 原本代码查询表有误，现更换查询方法
         * 查询表  supply_material  供货信息表
         *        supply_material_detail  供货信息详情表
         *        supply_material_r   供货信息副表
         *         MD_VENDOR   主数据供应商表
         *
         *   多表连查，查询送货信息等
         *   查询出，所有未入库的
         *   字段为R表中的status：0
         * */
        List<SupplyMaterialBeanVo> deliveryNoteHeadList = this.invInputHeadService.getSupplyMaterial(pages,supplyMaterialBeanVo);
       /* for(int i = 0; i < deliveryNoteHeadList.size(); i++){
            String is_invoice = deliveryNoteHeadList.get(i).getIs_invoice();
            Map<String,String> a = datasetCommonService.getDictByKey(is_invoice);
            System.out.println(a);
        }*/





        //采购订单类型
        Map poTypeMap = this.datasetCommonService.getPOType();
        //状态
        Map poStatusMap = com.erp.order.po.dao.data.DataBox.getPoStatusMap();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //获取项目
        Map projectMap = this.masterDataCommonService.getProjectMap();


        //页面属性设置
        model.addAttribute("deliveryNoteHeadList", deliveryNoteHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("projectMap", projectMap);

        return "invInput/pop/selectDeliveryNoteModal";
    }



    /**
     *
     * @description 入库编辑数据
     * @date 2020-08-20 17:21:04
     * @author
     * @param invInputVO
     * @param
     * @param model
     * @return String
     *
     */
    @RequestMapping("editInvInputHead")
    public String editInvInputHead(InvInputVO invInputVO, InvInputHead invInputHead, Model model, RedirectAttributes attr) {

        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        String code = staffInfo.getStaffCode();
        String dCode = staffInfo.getDepartmentCode();

        String inputManner = invInputVO.getInputManner();
        if(inputManner.equals("1")){
            //为1则添加入库表
            invInputHead.setInputHeadCode(invInputVO.getInputHeadCode());
            invInputHead.setInputType(invInputVO.getInputType());
            invInputHead.setInputSourceType(invInputVO.getInputSourceType());
            invInputHead.setInputSourceHeadCode(invInputVO.getInputSourceHeadCode());
            String warehouseCode = invInputVO.getWarehouseCode();
            invInputHead.setWarehouseCode(warehouseCode);
            String file = invInputVO.getFile();
            if(StringUtils.isNotEmpty(file)){
                String fl = file.substring(0,file.length() - 1);
                invInputVO.setFile(fl);
                invInputVO.setIs_bill(0);
            }else{
                invInputVO.setFile(file);
                invInputVO.setIs_bill(1);
            }


            String testingFile = invInputVO.getTestingFile();
            if(StringUtils.isNotEmpty(testingFile)){
                String tFile = testingFile.substring(0,testingFile.length() - 1);
                invInputVO.setTestingFile(tFile);
                invInputVO.setIsTesting("0");
            }else{
                invInputVO.setTestingFile(testingFile);
                invInputVO.setIsTesting("1");
            }

            invInputHead.setFile(invInputVO.getFile());
            invInputHead.setTestingFile(invInputVO.getTestingFile());
            invInputHead.setIsTesting(invInputVO.getIsTesting());

            SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
            try{
                Date date = dateStr.parse(invInputVO.getInputDate());
                invInputHead.setInputDate(date);
            }catch (ParseException e){

            }

            invInputHead.setMemo(invInputVO.getMemo());
            invInputHead.setVersion(1);
            invInputHead.setApproveStatus("UNSUBMIT");
            invInputHead.setStatus(invInputVO.getStatus());
            invInputHead.setStaffCode(code);
            invInputHead.setDepartmentCode(dCode);
            invInputHead.setIsDel("0");
            Date date = new Date();
            invInputHead.setCreatedDate(date);
            invInputHead.setCreatedBy(ShiroUtil.getPrincipal());
            invInputHead.setOrgCode("erp.com");
            invInputHead.setIs_bill(invInputVO.getIs_bill());
            invInputHead.setInputManner(invInputVO.getInputManner());
            invInputHeadService.insertDataObject(invInputHead);


            String a =  "["+invInputVO.getJSONText()+"]";


            JSONArray array = JSONArray.fromObject(a);
            array.toArray();

            for(int i = 0; i < array.size();i++){
                String material_code = array.getJSONObject(i).getString("material_code");
                String price = array.getJSONObject(i).getString("price");
                String standard_unit = array.getJSONObject(i).getString("standard_unit");
                String allPrice = array.getJSONObject(i).getString("allPrice");
                String input_quantity = array.getJSONObject(i).getString("input_quantity");


                String loss = array.getJSONObject(i).getString("loss");
                String attached = array.getJSONObject(i).getString("attached");
                String attached_memo = array.getJSONObject(i).getString("attached_memo");

                InvInputLine invInputLine = new InvInputLine();

                String inputLineCode = SnowFlake.getConcurrentId().toString();
                invInputLine.setInputLineCode(inputLineCode);
                invInputLine.setInputHeadCode(invInputVO.getInputHeadCode());
                invInputLine.setInputSourceLineCode("1");
                invInputLine.setMaterialCode(material_code);
                invInputLine.setQuantity(new BigDecimal("1"));
                BigDecimal big = new BigDecimal(input_quantity);
                invInputLine.setInputQuantity(big);
                invInputLine.setPrice(new BigDecimal(price));
                invInputLine.setAmount(new BigDecimal(allPrice));
                invInputLine.setAttached(attached);
                invInputLine.setAttachedMemo(attached_memo);
                invInputLine.setLoss(loss);
                invInputLine.setLossMemo("");
                invInputLine.setDiscount("");
                invInputLine.setDiscountMemo("");
                invInputLine.setIsReport("0");
                invInputLine.setUnit(standard_unit);
                invInputLine.setVersion(1);
                invInputLine.setStatus("");
                invInputLine.setIsDel("0");
                invInputLine.setCreatedDate(new Date());
                invInputLine.setCreatedBy(ShiroUtil.getPrincipal());
                invInputLine.setOrgCode("erp.com");
                invInputLineService.insertDataObject(invInputLine);


                InvStock invStock = new InvStock();

                invStock.setStockCode(SnowFlake.getConcurrentId().toString());
                invStock.setWarehouseCode(warehouseCode);
                invStock.setMaterialCode(material_code);
                invStock.setStockNumber(big);
                invStock.setRetainFlag("N");
                invStock.setBillType("INPUT");
                invStock.setBillHeadCode(invInputVO.getInputHeadCode());
                invStock.setBillLineCode(inputLineCode);
                invStock.setMemo("");
                invStock.setStatus("Y");
                invStock.setStaffCode(code);
                invStock.setDepartmentCode(dCode);
                invStock.setCreatedDate(new Date());
                invStock.setCreatedBy(ShiroUtil.getPrincipal());
                invStock.setOrgCode("erp.com");

                invStockService.insertDataObject(invStock);

            }
        }else{
            //为0则入库表，出库表都插入

            invInputHead.setInputHeadCode(invInputVO.getInputHeadCode());
            invInputHead.setInputType(invInputVO.getInputType());
            invInputHead.setInputSourceType(invInputVO.getInputSourceType());
            invInputHead.setInputSourceHeadCode(invInputVO.getInputSourceHeadCode());
            String warehouseCode = invInputVO.getWarehouseCode();
            invInputHead.setWarehouseCode(warehouseCode);
            String file = invInputVO.getFile();
            if(StringUtils.isNotEmpty(file)){
                String fl = file.substring(0,file.length() - 1);
                invInputVO.setFile(fl);
                invInputVO.setIs_bill(0);
            }else{
                invInputVO.setFile(file);
                invInputVO.setIs_bill(1);
            }


            String testingFile = invInputVO.getTestingFile();
            if(StringUtils.isNotEmpty(testingFile)){
                String tFile = testingFile.substring(0,testingFile.length() - 1);
                invInputVO.setTestingFile(tFile);
                invInputVO.setIsTesting("0");
            }else{
                invInputVO.setTestingFile(testingFile);
                invInputVO.setIsTesting("1");
            }

            invInputHead.setFile(invInputVO.getFile());
            invInputHead.setTestingFile(invInputVO.getTestingFile());
            invInputHead.setIsTesting(invInputVO.getIsTesting());

            SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            try{
                date = dateStr.parse(invInputVO.getInputDate());
                invInputHead.setInputDate(date);
            }catch (ParseException e){

            }

            invInputHead.setMemo(invInputVO.getMemo());
            invInputHead.setVersion(1);
            invInputHead.setApproveStatus("UNSUBMIT");
            invInputHead.setStatus(invInputVO.getStatus());
            invInputHead.setStaffCode(code);
            invInputHead.setDepartmentCode(dCode);
            invInputHead.setIsDel("0");
            Date createDate = new Date();
            invInputHead.setCreatedDate(createDate);
            invInputHead.setCreatedBy(ShiroUtil.getPrincipal());
            invInputHead.setOrgCode("erp.com");
            invInputHead.setIs_bill(invInputVO.getIs_bill());
            invInputHead.setInputManner(invInputVO.getInputManner());
            invInputHeadService.insertDataObject(invInputHead);

            //插入出库单头表
            InvOutputHead invOutputHead = new InvOutputHead();
            String outputHeadCode = "CK" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN");
            invOutputHead.setOutputHeadCode(outputHeadCode);
            invOutputHead.setOutputDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            invOutputHead.setStaffCode(code);
            invOutputHead.setDepartmentCode(dCode);
            invOutputHead.setIsDel("0");
            invOutputHead.setCreatedDate(date);
            invOutputHead.setCreatedBy(ShiroUtil.getPrincipal());
            invOutputHead.setOrgCode("erp.com");
            invOutputHead.setApproveStatus("UNSUBMIT");
            invOutputHead.setStatus("UNDONE");
            invOutputHeadService.insertDataObject(invOutputHead);


            String a =  "["+invInputVO.getJSONText()+"]";

            JSONArray array = JSONArray.fromObject(a);
            array.toArray();

            for(int i = 0; i < array.size();i++){
                String material_code = array.getJSONObject(i).getString("material_code");
                String price = array.getJSONObject(i).getString("price");
                String standard_unit = array.getJSONObject(i).getString("standard_unit");
                String allPrice = array.getJSONObject(i).getString("allPrice");
                String input_quantity = array.getJSONObject(i).getString("input_quantity");


                String loss = array.getJSONObject(i).getString("loss");
                String attached = array.getJSONObject(i).getString("attached");
                String attached_memo = array.getJSONObject(i).getString("attached_memo");

                InvInputLine invInputLine = new InvInputLine();

                String inputLineCode = SnowFlake.getConcurrentId().toString();
                invInputLine.setInputLineCode(inputLineCode);
                invInputLine.setInputHeadCode(invInputVO.getInputHeadCode());
                invInputLine.setInputSourceLineCode("1");
                invInputLine.setMaterialCode(material_code);
                invInputLine.setQuantity(new BigDecimal("1"));
                BigDecimal big = new BigDecimal(input_quantity);
                invInputLine.setInputQuantity(big);
                invInputLine.setPrice(new BigDecimal(price));
                invInputLine.setAmount(new BigDecimal(allPrice));
                invInputLine.setAttached(attached);
                invInputLine.setAttachedMemo(attached_memo);
                invInputLine.setLoss(loss);
                invInputLine.setLossMemo("");
                invInputLine.setDiscount("");
                invInputLine.setDiscountMemo("");
                invInputLine.setIsReport("0");
                invInputLine.setUnit(standard_unit);
                invInputLine.setVersion(1);
                invInputLine.setStatus("");
                invInputLine.setIsDel("0");
                invInputLine.setCreatedDate(new Date());
                invInputLine.setCreatedBy(ShiroUtil.getPrincipal());
                invInputLine.setOrgCode("erp.com");
                invInputLineService.insertDataObject(invInputLine);


                InvStock invStock = new InvStock();

                invStock.setStockCode(SnowFlake.getConcurrentId().toString());
                invStock.setWarehouseCode(warehouseCode);
                invStock.setMaterialCode(material_code);
                invStock.setStockNumber(big);
                invStock.setRetainFlag("N");
                invStock.setBillType("INPUT");
                invStock.setBillHeadCode(invInputVO.getInputHeadCode());
                invStock.setBillLineCode(inputLineCode);
                invStock.setMemo("");
                invStock.setStatus("Y");
                invStock.setStaffCode(code);
                invStock.setDepartmentCode(dCode);
                invStock.setCreatedDate(new Date());
                invStock.setCreatedBy(ShiroUtil.getPrincipal());
                invStock.setOrgCode("erp.com");

                invStockService.insertDataObject(invStock);



                //插入出库行表
                InvOutputLine invOutputLine = new InvOutputLine();
                String outputLineCode = SnowFlake.getConcurrentId().toString();
                invOutputLine.setOutputLineCode(outputLineCode);
                invOutputLine.setOutputHeadCode(outputHeadCode);
                invOutputLine.setMaterialCode(material_code);
                invOutputLine.setOutputQuantity(big.negate());
                invOutputLine.setCreatedDate(date);
                invOutputLine.setCreatedBy(ShiroUtil.getPrincipal());
                invOutputLine.setOrgCode("erp.com");
                invOutputLineService.insertDataObject(invOutputLine);


                //插入记录表
                 InvStock invStock1 = new InvStock();

                invStock1.setStockCode(SnowFlake.getConcurrentId().toString());
                invStock1.setWarehouseCode(warehouseCode);
                invStock1.setMaterialCode(material_code);
                invStock1.setStockNumber(big.negate());
                invStock1.setRetainFlag("N");
                invStock1.setBillType("OUTPUT");
                invStock1.setBillHeadCode(outputHeadCode);
                invStock1.setBillLineCode(outputLineCode);
                invStock1.setMemo("");
                invStock1.setStatus("Y");
                invStock1.setStaffCode(code);
                invStock1.setDepartmentCode(dCode);
                invStock1.setCreatedDate(new Date());
                invStock1.setCreatedBy(ShiroUtil.getPrincipal());
                invStock1.setOrgCode("erp.com");

                invStockService.insertDataObject(invStock1);


            }

        }



        attr.addFlashAttribute("hint", "success");

        return "redirect:getInvInputHeadList";
    }


    /**
     *
     * @description 退货编辑数据
     * @date 2020-08-20 17:21:04
     * @author
     * @param invInputVO
     * @param
     * @param model
     * @return String
     *
     */
    @RequestMapping("editInvInputHeadReturn")
    public String editInvInputHeadReturn(InvInputVO invInputVO, InvInputHead invInputHead, Model model, RedirectAttributes attr) {

        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        String code = staffInfo.getStaffCode();
        String dCode = staffInfo.getDepartmentCode();

        //String inputHeadCode = "RE" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN");
        invInputHead.setInputHeadCode(invInputVO.getInputHeadCode());
        invInputHead.setInputType(invInputVO.getInputType());
        invInputHead.setInputSourceType(invInputVO.getInputSourceType());
        invInputHead.setInputSourceHeadCode(invInputVO.getInputSourceHeadCode());
        String warehouseCode = invInputVO.getWarehouseCode();
        invInputHead.setWarehouseCode(warehouseCode);
        invInputHead.setFile(invInputVO.getFile());

        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date date = dateStr.parse(invInputVO.getInputDate());
            invInputHead.setInputDate(date);
        }catch (ParseException e){

        }

        invInputHead.setMemo(invInputVO.getMemo());
        invInputHead.setVersion(1);
        invInputHead.setApproveStatus("UNSUBMIT");
        invInputHead.setStatus(invInputVO.getStatus());
        invInputHead.setStaffCode(code);
        invInputHead.setDepartmentCode(dCode);
        invInputHead.setIsDel("0");
        Date date = new Date();
        invInputHead.setCreatedDate(date);
        invInputHead.setCreatedBy(ShiroUtil.getPrincipal());
        invInputHead.setOrgCode("erp.com");
        invInputHeadService.insertDataObject(invInputHead);


        String a =  "["+invInputVO.getJSONText()+"]";


        JSONArray array = JSONArray.fromObject(a);
        array.toArray();

        for(int i = 0; i < array.size();i++){
            String material_code = array.getJSONObject(i).getString("material_code");
            String price = array.getJSONObject(i).getString("price");
            String standard_unit = array.getJSONObject(i).getString("standard_unit");
            String allPrice = array.getJSONObject(i).getString("allPrice");
            String input_quantity = array.getJSONObject(i).getString("input_quantity");


            InvInputLine invInputLine = new InvInputLine();

            String inputLineCode = SnowFlake.getConcurrentId().toString();
            invInputLine.setInputLineCode(inputLineCode);
            invInputLine.setInputHeadCode(invInputVO.getInputHeadCode());
            invInputLine.setInputSourceLineCode("1");
            invInputLine.setMaterialCode(material_code);
            invInputLine.setQuantity(new BigDecimal("1"));
            BigDecimal big = new BigDecimal(input_quantity);
            invInputLine.setInputQuantity(big.negate());
            invInputLine.setPrice(new BigDecimal(price));
            invInputLine.setAmount(new BigDecimal(allPrice));
            invInputLine.setAttached("");
            invInputLine.setAttachedMemo("");
            invInputLine.setLoss("");
            invInputLine.setLossMemo("");
            invInputLine.setDiscount("");
            invInputLine.setDiscountMemo("");
            invInputLine.setIsReport("0");
            invInputLine.setUnit(standard_unit);
            invInputLine.setVersion(1);
            invInputLine.setStatus("");
            invInputLine.setIsDel("0");
            invInputLine.setCreatedDate(new Date());
            invInputLine.setCreatedBy(ShiroUtil.getPrincipal());
            invInputLine.setOrgCode("erp.com");
            invInputLineService.insertDataObject(invInputLine);


            InvStock invStock = new InvStock();

            invStock.setStockCode(SnowFlake.getConcurrentId().toString());
            invStock.setWarehouseCode(warehouseCode);
            invStock.setMaterialCode(material_code);
            invStock.setStockNumber(big.negate());
            invStock.setRetainFlag("N");
            invStock.setBillType("INPUT");
            invStock.setBillHeadCode(invInputVO.getInputHeadCode());
            invStock.setBillLineCode(inputLineCode);
            invStock.setMemo("");
            invStock.setStatus("Y");
            invStock.setStaffCode(code);
            invStock.setDepartmentCode(dCode);
            invStock.setCreatedDate(new Date());
            invStock.setCreatedBy(ShiroUtil.getPrincipal());
            invStock.setOrgCode("erp.com");

            invStockService.insertDataObject(invStock);

        }
        attr.addFlashAttribute("hint", "success");
       /* Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getInvInputHead";
        }

        try {
            //对当前编辑的对象初始化默认的字段
            //系统生成inputHeadCode
            if(StringUtils.isEmpty(invInputHead.getInputHeadCode())){
                invInputHead.setInputHeadCode(invInputHead.getInputType() + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType(invInputHead.getInputType()));
            }

            //保存编辑的数据
            this.invInputHeadService.insertOrUpdateDataObject(invInputHead);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("inputHeadCode", invInputHead.getInputHeadCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "单据编码已存在，请重新输入");
                return "redirect:getInvInputHeadList";
            }else {
                throw e;
            }
        }*/

        return "redirect:getInvInputHeadReturnList";
    }



    /**
     *
     * @description 换货编辑数据
     * @date 2020-08-20 17:21:04
     * @author
     * @param invInputVO
     * @param
     * @param model
     * @return String
     *
     */
    @RequestMapping("editInvInputHeadSwap")
    public String editInvInputHeadSwap(InvInputVO invInputVO, InvInputHead invInputHead, Model model, RedirectAttributes attr) {

        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        String code = staffInfo.getStaffCode();
        String dCode = staffInfo.getDepartmentCode();

        //String inputHeadCode = "SW" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN");
        invInputHead.setInputHeadCode(invInputVO.getInputHeadCode());
        invInputHead.setInputType(invInputVO.getInputType());
        invInputHead.setInputSourceType(invInputVO.getInputSourceType());
        invInputHead.setInputSourceHeadCode(invInputVO.getInputSourceHeadCode());
        String warehouseCode = invInputVO.getWarehouseCode();
        invInputHead.setWarehouseCode(warehouseCode);
        invInputHead.setFile(invInputVO.getFile());

        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date date = dateStr.parse(invInputVO.getInputDate());
            invInputHead.setInputDate(date);
        }catch (ParseException e){

        }

        invInputHead.setMemo(invInputVO.getMemo());
        invInputHead.setVersion(1);
        invInputHead.setApproveStatus("UNSUBMIT");
        invInputHead.setStatus(invInputVO.getStatus());
        invInputHead.setStaffCode(code);
        invInputHead.setDepartmentCode(dCode);
        invInputHead.setIsDel("0");
        Date date = new Date();
        invInputHead.setCreatedDate(date);
        invInputHead.setCreatedBy(ShiroUtil.getPrincipal());
        invInputHead.setOrgCode("erp.com");
        invInputHeadService.insertDataObject(invInputHead);


        String a =  "["+invInputVO.getJSONText()+"]";


        JSONArray array = JSONArray.fromObject(a);
        array.toArray();

        for(int i = 0; i < array.size();i++){
            String material_code = array.getJSONObject(i).getString("material_code");
            String price = array.getJSONObject(i).getString("price");
            String standard_unit = array.getJSONObject(i).getString("standard_unit");
            String allPrice = array.getJSONObject(i).getString("allPrice");
            String input_quantity = array.getJSONObject(i).getString("input_quantity");




            InvInputLine invInputLine = new InvInputLine();

            String inputLineCode = SnowFlake.getConcurrentId().toString();
            invInputLine.setInputLineCode(inputLineCode);
            invInputLine.setInputHeadCode(invInputVO.getInputHeadCode());
            invInputLine.setInputSourceLineCode("1");
            invInputLine.setMaterialCode(material_code);
            invInputLine.setQuantity(new BigDecimal("1"));
            BigDecimal big = new BigDecimal(input_quantity);
            invInputLine.setInputQuantity(big.negate());
            invInputLine.setPrice(new BigDecimal(price));
            invInputLine.setAmount(new BigDecimal(allPrice));
            invInputLine.setAttached("");
            invInputLine.setAttachedMemo("");
            invInputLine.setLoss("");
            invInputLine.setLossMemo("");
            invInputLine.setDiscount("");
            invInputLine.setDiscountMemo("");
            invInputLine.setIsReport("0");
            invInputLine.setUnit(standard_unit);
            invInputLine.setVersion(1);
            invInputLine.setStatus("");
            invInputLine.setIsDel("0");
            invInputLine.setCreatedDate(new Date());
            invInputLine.setCreatedBy(ShiroUtil.getPrincipal());
            invInputLine.setOrgCode("erp.com");
            invInputLineService.insertDataObject(invInputLine);


            InvStock invStock = new InvStock();

            invStock.setStockCode(SnowFlake.getConcurrentId().toString());
            invStock.setWarehouseCode(warehouseCode);
            invStock.setMaterialCode(material_code);
            invStock.setStockNumber(big.negate());
            invStock.setRetainFlag("N");
            invStock.setBillType("INPUT");
            invStock.setBillHeadCode(invInputVO.getInputHeadCode());
            invStock.setBillLineCode(inputLineCode);
            invStock.setMemo("");
            invStock.setStatus("Y");
            invStock.setStaffCode(code);
            invStock.setDepartmentCode(dCode);
            invStock.setCreatedDate(new Date());
            invStock.setCreatedBy(ShiroUtil.getPrincipal());
            invStock.setOrgCode("erp.com");

            invStockService.insertDataObject(invStock);

        }
        attr.addFlashAttribute("hint", "success");
       /* Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getInvInputHead";
        }

        try {
            //对当前编辑的对象初始化默认的字段
            //系统生成inputHeadCode
            if(StringUtils.isEmpty(invInputHead.getInputHeadCode())){
                invInputHead.setInputHeadCode(invInputHead.getInputType() + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType(invInputHead.getInputType()));
            }

            //保存编辑的数据
            this.invInputHeadService.insertOrUpdateDataObject(invInputHead);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("inputHeadCode", invInputHead.getInputHeadCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "单据编码已存在，请重新输入");
                return "redirect:getInvInputHeadList";
            }else {
                throw e;
            }
        }*/

        return "redirect:getInvInputHeadSwapList";
    }


    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-08-20 17:21:04
     * @author 
     * @param invInputHead
     * @return String
     *
     */
    @RequestMapping("deleteInvInputHead")
    public String deleteInvInputHead(InvInputHead invInputHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if(invInputHead!=null&&invInputHead.getInputHeadId()!=null) {
            if(invInputHead.getStatus().equals("NEW")) {
                //删除数据
                this.invInputHeadService.deleteDataObject(invInputHead);
                
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态的入库单不能删除");
            }
        }
        
        return "redirect:getInvInputHeadList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {

            //更新审核状态
            this.invInputHeadService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("inputHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("inputHeadCode", code);
        }
        
        return "redirect:getInvInputHead";
    }
    
    
    
    /**
     * 
     * @description 自动创建凭证分录
     * @date 2020年9月25日
     * @author dongbin
     * @param headCode
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreateVoucherEntry")
    @ResponseBody
    public String autoCreateVoucherEntry(String headCode, String inputType){
        try {
            //转换入库类型为单据类型
            String billType = com.erp.common.voucher.dao.data.DataBox.getVoucherTypeByBusinessType(inputType);
            
            //删除自动生成的凭证和分录
            //根据单据头code获取凭证头code
            String voucherHeadCode = this.finVoucherBillRService.getVoucherHeadCodeByBillHeadCode(billType, headCode);
            //删除凭证
            if(StringUtils.isNotBlank(voucherHeadCode)) {
                this.finVoucherHeadService.deleteFinVoucherHeadByVoucherHeadCode(voucherHeadCode);
            }
            
            //自动生成凭证和分录
            //计算分录的金额
            //获取入库行
            List<InvInputLine> inputLineList = this.invInputLineService.getInvInputLineListByInputHeadCode(headCode);
            
            BigDecimal voucherAmount = new BigDecimal(0D);
            //循环获取加和入库数量和物料单价
            for(InvInputLine invInputLine: inputLineList) {
                BigDecimal quantity = invInputLine.getInputQuantity();
                //获取采购订单行
                PoLine poLine = this.poLineService.getDataObject(invInputLine.getInputSourceLineCode());
                BigDecimal price = poLine.getPrice();
                //计算行金额
                BigDecimal lineAmount = quantity.multiply(price);
                //计算合计金额
                voucherAmount = voucherAmount.add(lineAmount);
            }
            
            //调用自动创建方法
            this.finVoucherModelHeadService.autoCreateVoucher(headCode, new Double[]{voucherAmount.doubleValue()}, billType);
            
            return JsonDataUtil.getExecuteJson(0);
        }catch(Exception e) {
            return JsonDataUtil.getExecuteJson(-1, "重新生成分录错误");
        }
    }
}
